#include <iostream>
#include <string>
#include "Socket.hpp"
#include "protocol.hpp"
#include <ctime>
using namespace std;



int main(int argc, char* args[]) {
    if (argc != 3) {
        cout << "Usage:\n\t" << args[0] << " server_ip server_port\n" << endl;
        return 0;
    }
    string serverip = args[1];
    uint16_t serverport = stoi(args[2]);
    TcpSocket* socket = new TcpSocket(serverport);
    if (!socket->BuildConnectSocketMethod(serverip, serverport)) {
        return 0;
    }
    unique_ptr<Factory> fact = unique_ptr<Factory>(new Factory());
    srand(time(nullptr) ^ getpid() ^ pthread_self()); // 种一棵随机数种子
    const string opers = "+-*/%&^";
    while (true) {
        sleep(1);
        int x = rand() % 100;
        usleep(rand() % 8888);
        int y = rand() % 100;
        usleep(rand() % 7777);
        char op = opers[rand() % opers.size()];
        shared_ptr<Request> req = fact->BuildRequest(x, y, op);
        // 序列化
        string send_message = req->Serialize();
        string send_package = Encode(send_message);
        // 发送
        if (!socket->Send(send_package)) {
            break;
        }

        // 接收客户端返回
        string buffer;
        if (!socket->Recv(&buffer, 1024)) {
            break;
        }
        // 接收成功
        // 解包
        string message;
        while (Decode(buffer, &message)) {
            // 解包成功
            shared_ptr<Response> resp = fact->BuildResponse();
            // 反序列化
            resp->DeSerialize(message);
            cout << req->ToString() << "== " << resp->ToString() << endl;    
        }
    }
    return 0;
}